package com.zn.utils
{
    import com.greensock.TweenLite;
    import com.greensock.easing.Linear;
    
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.DisplayObject;
    import flash.display.DisplayObjectContainer;
    import flash.display.InteractiveObject;
    import flash.display.Stage;
    import flash.geom.Matrix;
    import flash.geom.Rectangle;

    /**
     *屏幕相关
     * @author zn
     *
     */
    public class SwapScreenUtil
    {
        private static var _oldScreenBitmap:Bitmap;

        private static var _newScreenBitmap:Bitmap;

        public static var gameRoot:Stage;

        public static var completeCallBack:Function;

        /**
         *绘制旧屏幕
         * @param obj
         * @param rect
         *
         */
        public static function setOldScreen():void
        {
            if (gameRoot == null)
                return;

            if (_oldScreenBitmap)
            {
                if (_oldScreenBitmap.bitmapData)
                    _oldScreenBitmap.bitmapData.dispose();

                if (_oldScreenBitmap.parent)
                    _oldScreenBitmap.parent.removeChild(_oldScreenBitmap);
            }

            _oldScreenBitmap = drawScreen();
            gameRoot.addChild(_oldScreenBitmap);
        }

        public static function swapScreen():void
        {
            if (_oldScreenBitmap == null || gameRoot == null)
                return;

            _oldScreenBitmap.visible = false;
            _newScreenBitmap = drawScreen();
            _oldScreenBitmap.visible = true;
            gameRoot.addChild(_newScreenBitmap);

            _newScreenBitmap.alpha = 0;
            TweenLite.to(_newScreenBitmap, 0.3, { alpha: 1, ease: Linear.easeNone, onComplete: swapScreenComplete });

            gameRoot.mouseChildren = false;
        }

        private static function swapScreenComplete():void
        {
            if (_oldScreenBitmap)
            {
                gameRoot.removeChild(_oldScreenBitmap);
                _oldScreenBitmap.bitmapData.dispose();
                _oldScreenBitmap = null;
            }

            if (_newScreenBitmap)
            {
                gameRoot.removeChild(_newScreenBitmap);
                _newScreenBitmap.bitmapData.dispose();
                _newScreenBitmap = null;
            }

            gameRoot.mouseChildren = true;
			
            if (completeCallBack != null)
			{
                completeCallBack();
				completeCallBack=null;
			}
        }

        private static function drawScreen():Bitmap
        {
            var w:Number = gameRoot.stage.stageWidth;
            var h:Number = gameRoot.stage.stageHeight;

            var bitmapData:BitmapData = new BitmapData(w, h, true, 0);
            bitmapData.draw(gameRoot);
            return new Bitmap(bitmapData);
        }
    }
}
